// 封装Storage
// 规定存储格式  mall={user:{name:'ruby',age:18},}

const STORAGE_KEY = 'mall'

export default {
  // 存储值
  setItem (key, val, moduleName) {
    if (moduleName) {
      // 在某个模块下新增属性
      // 获取模块
      const data = this.getItem(moduleName)
      data[key] = val
      this.setItem(moduleName, data)
    } else {
      // 存储模块
      const obj = this.getStorage()
      obj[key] = val
      // JSON.stringify() 将json格式的数据转换为字符串
      window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(obj))
    }
  },

  // 获取值
  // 获取某个模块下面的属性 比如getItem (name,user) 就是从mall中获取user模块下的name属性
  getItem (key, moduleName) {
    if (moduleName) {
      const val = this.getItem(moduleName)
      if (val) return val[key]
    }
    return this.getStorage()[key]
  },

  // 获取全部值
  getStorage () {
    return JSON.parse(window.sessionStorage.getItem(STORAGE_KEY) || '{}')
  },

  // 清空
  clear (key, moduleName) {
    const obj = this.getStorage()
    if (moduleName) {
      delete obj[moduleName][key]
    } else {
      delete obj[key]
    }
    window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(obj))
  }
}
